#!/usr/bin/perl
use strict;
use FindBin;

#my ($ITER, $RANGE) = (2000000, 10000);
#my ($ITER, $RANGE) = (20, 15);
my ($ITER, $RANGE) = (20000, 10);
#my ($ITER, $RANGE) = (20, 15);

print STDERR "\tGenerating test data\n";
use constant DIST  => 0;
use constant INDEX => 1;
my %id_pair_lowest;
my @id_pair_results;
for my $i (0..($ITER - 1))
{
	my $id1 =  int(rand($RANGE));
	my $id2 =  int(rand($RANGE));
	my $ids_normalized = ($id1 < $id2 ? ($id1."\t".$id2) : ($id2."\t".$id1));
	my $dist = rand(1000);
	if ($id1 == $id2)
	{
		$dist = 0;
	}
	push(@id_pair_results, "id_$id1\tid_$id2\t$dist\n");
	if (!exists $id_pair_lowest{$ids_normalized} ||
		$id_pair_lowest{$ids_normalized}[0] > $dist)
	{
		$id_pair_lowest{$ids_normalized} = [$dist, $i];
	}
}

print STDERR "\tWriting to results.test\n";
{
	open RESULTS, ">$FindBin::Bin/results.test";
	print RESULTS "seq1\tseq2\n----\t----\n";
	print RESULTS @id_pair_results;
}

print STDERR "\tWriting out closest pair to results.filtered.test\n";
{
	open RESULTS, ">$FindBin::Bin/results.filtered.test";
	my @indices = sort {$a <=> $b} map {$_->[1]} values %id_pair_lowest;
	print RESULTS $id_pair_results[$_ ] for (@indices);
}


print STDERR "\tRunning seq_pairs_lowest_pair...\n";
system("seq_pairs_lowest_pair -s -vv -i $FindBin::Bin/results.test > $FindBin::Bin/results.filtered.try.test");
print STDERR "\tComparing results...\n";
{
	my @diff = `diff $FindBin::Bin/results.filtered.test $FindBin::Bin/results.filtered.try.test`;
	if (@diff != 0)
	{
		print @diff;
		print STDERR "FAILED: $FindBin::Bin/results.filtered.test > $FindBin::Bin/results.filtered.try.test are not the same!\n";
		exit;
	}
}
print STDERR "\tCleaning up...\n";
#unlink (glob("$FindBin::Bin/*.test"));
print STDERR "\n\tSUCCESS!!!\n\n";

